import fs from 'fs'



class JsonFileManager {

  constructor(dir){

    this.dir = dir;
    this.upd = false;
    this.transferStr = "";
    this.json = "";
    fs.open(dir, 'a+', function (err, fd) {
      if (err) {
        fs.chmod(dir, 0x777)
      }
    })
  }

  get (key) {
    return new Promise((resolve, reject) => {
      if (this.json) {
        resolve(this.json[key])
        return
      }

      fs.readFile(this.dir, (err, data) => {
        if (err) {
          console.log(err)
        }
        if (!data || data.length === 0) {
          resolve()
          return
        }

        if (this.json) {
          resolve(this.json[key])
          return
        }

        this.json = JSON.parse(data.toString())
        resolve(this.json[key])
      })
    })
  }
  set (key, val) {
    return new Promise((resolve, reject) => {
      if( !this.json){
        this.get(key)
          .then( () => {
            if(!this.json){
              this.json = {}
            }
            this.json[key] = val
            this.updJson()
            resolve()
          })
      }
      this.json[key] = val
      this.updJson()
      resolve()
    })
  }
  updJson(){

      if (this.upd) {
        return
      }
      this.upd = true
      this.transferStr = JSON.stringify(this.json)
      fs.writeFile(this.dir, JSON.stringify(this.json), 'utf8', (res) => {
        this.upd = false
        if (this.transferStr !== JSON.stringify(this.json)) {
          this.updJson()
        }
      })

  }
}

export {JsonFileManager}
